// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  try {
    // 先查总数
    const countRes = await db.collection('bottles').count()
    const total = countRes.total
    if (total === 0) {
      return { code: 1, msg: '暂无漂流瓶' }
    }
    // 随机skip
    const randomIndex = Math.floor(Math.random() * total)
    const res = await db.collection('bottles').skip(randomIndex).limit(1).get()
    if (res.data.length > 0) {
      return { code: 0, bottle: res.data[0] }
    } else {
      return { code: 2, msg: '未找到漂流瓶' }
    }
  } catch (e) {
    return { code: 3, msg: '数据库查询失败', error: e }
  }
} 